﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace mvchotleweb.Controllers
{
    public class UserController : Controller
    {
        //
        // GET: /User/

        hotel.BLL.tb_user userbll = new hotel.BLL.tb_user();
        hotel.BLL.tb_webinfo webbll = new hotel.BLL.tb_webinfo();

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Dologin()
        {
            string res = "内部错误。请于管理员联系！";
            string username = Request.Form["name"];
            string pwd = Request.Form["pwd"];
            string code = Request.Form["code"];

            if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(pwd) && !string.IsNullOrEmpty(code))
            {
                hotel.Model.tb_user usermod = userbll.GetModel(username);

                if (Session["ValidateCode"].ToString() != code)
                {
                    //  ModelState.AddModelError("code", "validate code is error");
                    res = "验证码错误！！";
                }
                else if (usermod == null || usermod.passworld != pwd)
                {
                    res = "用户名或密码错误！！";
                }
                else
                {
                    res = "OK";
                    Session["USER"] = usermod;
                    FormsAuthentication.SetAuthCookie(usermod.username, true, FormsAuthentication.FormsCookiePath);
                    //把用户对象保存在票据里
                    FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket(1, usermod.username, DateTime.Now, DateTime.Now.AddTicks(FormsAuthentication.Timeout.Ticks), false, JsonConvert.SerializeObject(usermod));
                    //加密票据
                    string hashTicket = FormsAuthentication.Encrypt(Ticket);
                    HttpCookie userCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket);
                    Response.Cookies.Add(userCookie);

                }
            }
            else
            {
                res = "用户名/密码/验证码不能为空！！";
            }
            return Content(res);
        }

        public ActionResult GetValidateCode()
        {
            ValidateCode vCode = new ValidateCode();
            string code = vCode.CreateValidateCode(5);
            Session["ValidateCode"] = code;
            byte[] bytes = vCode.CreateValidateGraphic(code);
            return File(bytes, @"image/jpeg");
        }

        // [Authorize]
        public ActionResult LoginOut()
        {
            FormsAuthentication.SignOut();
            Session.Remove("USER");
            return RedirectToAction("Index", "Home");
        }

    }
}
